package com.enjoychain.www.security.controller.basic;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enjoychain.www.common.api.CompanyApi;
import com.enjoychain.www.common.pojo.FieldPojo;
import com.enjoychain.www.common.pojo.PojoParams;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.enjoychain.www.security.entity.CorpBasicInfo;
import com.enjoychain.www.security.service.ICorpBasicInfoService;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 客户基础信息表 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2022-12-30
 */
@Api(tags = "企业基础信息")
@RestController
@RequestMapping("/corpBasicInfo")
public class CorpBasicInfoController {

    @Autowired
    ICorpBasicInfoService service;

    @Autowired
    CompanyApi companyApi;


    @PreAuthorize("@ss.hasPermi('client:service:list')")
    @GetMapping(path = "/list", produces = {"application/json"})
    @ApiOperation(value = "获取客户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "certNo", value = "统一社会信用代码",paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "customName", value = "客户名称，支持模糊搜索", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "busiType", value = "业务类型，支持多选，中间以逗号分割",allowableValues = "SAFE,ENVIRONMENT",paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "pageNo", value = "页码", paramType = "query", dataType = "long"),
            @ApiImplicitParam(name = "pageSize", value = "页面记录条数", paramType = "query", dataType = "long")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response= CorpBasicInfo.class),
    })
    public AjaxResult list(@RequestParam(value = "certNo", required = false) String certNo,
                           @RequestParam(value = "customName", required = false) String customName,
                           @RequestParam(value = "busiType", required = false)  String busiType,
                           @RequestParam(value = "keywords", required = false) String keywords,
                           @RequestParam(name = "pageNum", defaultValue = "1") long pageNum,
                           @RequestParam(name = "pageSize",defaultValue = "10") long pageSize)
    {

        IPage<CorpBasicInfo> corpBasicInfoIPage = new Page<>(pageNum, pageSize);
        SysUser loginUser = SecurityUtils.getLoginUser().getUser();
        QueryWrapper<CorpBasicInfo> queryWrapper = new QueryWrapper<>();
        if (loginUser.getRoles() != null && loginUser.getRoles().size() == 1 && loginUser.getRoles().get(0).getRoleId() == 4L){
            queryWrapper.eq("id",loginUser.getCompanyIds());
        }else {
            if (StringUtils.isNotEmpty(certNo)) {
                queryWrapper.eq("cert_no", certNo);
            }
            if (StringUtils.isNotEmpty(customName)) {
                queryWrapper.like("name", customName);
            }
            //待测试
            if (StringUtils.isNotEmpty(busiType)) {
                queryWrapper.eq("busi_type", busiType);
            }
            if (StringUtils.isNotEmpty(keywords)){
                queryWrapper.like("name", keywords).or().like("link_name",keywords);
            }
        }
        return AjaxResult.success("list-corp",service.page(corpBasicInfoIPage,queryWrapper));
    }


    @PreAuthorize("@ss.hasPermi('client:service:detail')")
    @GetMapping(value = "/detail", produces = {"application/json"})
    @ApiOperation("客户详细基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "certNo", value = "统一社会信用代码",paramType = "query", dataType = "String")
    })
    public AjaxResult getDetailInfo(@RequestParam(value = "certNo", required = false) String certNo)
    {
        PojoParams params = PojoParams.builder().inFields(FieldPojo.builder().ORGNUM(certNo).build()).build();

        return AjaxResult.success("list-corp",companyApi.getCompBasicInfo(params));
    }

    @PreAuthorize("@ss.hasPermi('client:service:find')")
    @GetMapping(value = "/find", produces = {"application/json"})
    @ApiOperation("模糊搜索公司想你想")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpName", value = "公司名称",paramType = "query", dataType = "String")
    })
    public AjaxResult findCompanyInfo(@RequestParam(value = "corpName", required = false) String corpName,
                                      @RequestParam(value = "pageSize", required = false) int pageSize,
                                      @RequestParam(value = "pageNum", required = false) int pageNum)
    {
        PojoParams params = PojoParams.builder().inFields(FieldPojo.builder()._COMPANY_NM(corpName).build()).pageSize(pageSize).pageNo(pageNum).build();
        return AjaxResult.success("list-corp",companyApi.findCompanyList(params));
    }



    @PreAuthorize("@ss.hasPermi('client:service:query')")
    @GetMapping(value = "{id}")
    @ApiOperation("客户基本信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id",paramType = "path", dataType = "String")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = CorpBasicInfo.class)
    })
    public AjaxResult getBasicInfo(@PathVariable(value = "id", required = false) String id)
    {
        return AjaxResult.success("list-corp",service.getById(id));
    }


    @PreAuthorize("@ss.hasPermi('client:service:add')")
    @PostMapping(consumes = {"application/json"}, produces = {"application/json"})
    @ApiOperation("新增客户基础信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = CorpBasicInfo.class),
    })
    @Log(title = "企业基础信息", businessType = BusinessType.INSERT)
    public AjaxResult add(@RequestBody CorpBasicInfo corpBasicInfo){
        String id = UUID.randomUUID().toString().replace("-","");
        corpBasicInfo.setId(id);
        return service.save(corpBasicInfo)? AjaxResult.success("add-corp",service.getById(id)): AjaxResult.error("新增客户基础信息失败");
    }


    @PreAuthorize("@ss.hasPermi('client:service:update')")
    @PutMapping(consumes = {"application/json"}, produces = {"application/json"})
    @ApiOperation("修改客户基础信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = CorpBasicInfo.class),
    })
    @Log(title = "企业基础信息", businessType = BusinessType.UPDATE)
    public AjaxResult update(@RequestBody CorpBasicInfo corpBasicInfo){
        String operate = "update-corp";
        return service.updateById(corpBasicInfo)?AjaxResult.success(operate,service.getById(corpBasicInfo.getId())) : AjaxResult.error("修改客户基础信息失败");
    }

    @PreAuthorize("@ss.hasPermi('client:service:delete')")
    @DeleteMapping(value = "{id}", produces = {"application/json"})
    @ApiOperation("删除客户基础信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AjaxResult.class),
    })
    @Log(title = "企业基础信息", businessType = BusinessType.DELETE)
    public AjaxResult delete(@PathVariable(value = "id", required = false) String id){
        String operate = "delete-corp";
        String[] ids = id.split(",");
        return service.removeBatchByIds(Arrays.asList(ids))?AjaxResult.success(operate) : AjaxResult.error("修改客户基础信息失败");
    }



    @Log(title = "企业基础信息", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('client:service:export')")
    @PostMapping("/export")
    @ApiOperation("导出客户基础信息")
    @ApiResponses({
            @ApiResponse(code = 200, message = "ok", response = AjaxResult.class),
    })
    @ApiImplicitParams({
            @ApiImplicitParam(name = "certNo", value = "统一社会信用代码",paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "customName", value = "客户名称，支持模糊搜索", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "busiType", value = "业务类型，支持多选，中间以逗号分割",allowableValues = "SAFE,ENVIRONMENT",paramType = "query", dataType = "String"),
    })
    public void export(@RequestParam(value = "certNo", required = false) String certNo,
                             @RequestParam(value = "customName", required = false) String customName,
                             @RequestParam(value = "busiType", required = false)  String busiType,
                             HttpServletResponse response
                             )
    {
        QueryWrapper<CorpBasicInfo> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(certNo)){
            queryWrapper.eq("cert_no",certNo);
        }
        if(StringUtils.isNotEmpty(customName)){
            queryWrapper.like("name",customName);
        }
        //待测试
        if(StringUtils.isNotEmpty(busiType)){
            queryWrapper.in("busi_type",busiType.split(","));
        }
        List<CorpBasicInfo> list = service.list(queryWrapper);
        ExcelUtil<CorpBasicInfo> util = new ExcelUtil<CorpBasicInfo>(CorpBasicInfo.class);
        util.exportExcel(response,list, "客户数据");
    }

    @ApiOperation("导入客户基础信息")
    @Log(title = "客户数据导入", businessType = BusinessType.IMPORT)
    @PostMapping(value = "/importData", consumes = "multipart/form-data")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "文件",paramType = "FORM", dataType="file")
                })
    public AjaxResult importData(MultipartFile file) throws Exception
    {
        ExcelUtil<CorpBasicInfo> util = new ExcelUtil<CorpBasicInfo>(CorpBasicInfo.class);
        List<CorpBasicInfo> corpBasicInfos = util.importExcel(file.getInputStream());
        for (CorpBasicInfo corpBasicInfo : corpBasicInfos){
            if (StringUtils.isEmpty(corpBasicInfo.getId())){
                corpBasicInfo.setId(UUID.randomUUID().toString().replace("-",""));
            }
        }
        return service.saveOrUpdateBatch(corpBasicInfos)?AjaxResult.success("批量插入成功"):AjaxResult.error("批量插入失败");
    }

    @ApiOperation("客户基础信息导入模板下载")
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<CorpBasicInfo> util = new ExcelUtil<CorpBasicInfo>(CorpBasicInfo.class);
        util.importTemplateExcel(response,"用户数据");
    }


    @PostMapping("/company_info")
    public Object getCompanyInfo(@RequestBody Object params)
    {
        return companyApi.getCompInfo(params);
    }

    @PostMapping("/compy_shareholder")
    public Object getCompShareholder(@RequestBody Object params)
    {
        return companyApi.getCompShareholder(params);
    }
    @PostMapping("/company_manager")
    public Object getCompManager(@RequestBody Object params)
    {
        return companyApi.getCompManager(params);
    }
    @PostMapping("/company_branch")
    public Object getCompBranch(@RequestBody Object params)
    {
        return companyApi.getCompanyBranch(params);
    }
    @PostMapping("/company_honesty")
    public Object getCompHonesty(@RequestBody Object params)
    {
        return companyApi.getCompanyHonesty(params);
    }
    @PostMapping("/company_dishonest")
    public Object getCompDisHonest(@RequestBody Object params)
    {
        return companyApi.getCompDisHonest(params);
    }
    @PostMapping("/company_manage")
    public Object getManage(@RequestBody Object params)
    {
        return companyApi.getCompManage(params);
    }

    @PostMapping("/LAW_LITIGANT_BASICINFO_JX")
    public Object getLawLitigantBasicInfoJx(@RequestBody Object params)
    {
        return companyApi.getLawLitigantBasicInfoJx(params);
    }

    @PostMapping("/LAW_DISHONEST_BASICINFO_JX")
    public Object getLawDisHonestBasicInfoJx(@RequestBody Object params)
    {
        return companyApi.getLawDisHonestBasicInfoJx(params);
    }
    @PostMapping("/LAW_JUDICIAL_BASICINFO_JX")
    public Object getLawJudicialBasicInfoJx(@RequestBody Object params)
    {
        return companyApi.getLawJudicialBasicInfoJx(params);
    }
    @PostMapping("/LAW_COURT_ANNE_BASICINFO_JX")
    public Object getLawCourtAnneBasicInfoJx(@RequestBody Object params)
    {
        return companyApi.getLawCourtAnneBasicInfoJx(params);
    }

    @PostMapping("/COMPANY_OPEREXCEPT_XYGS")
    public Object getCompOperExceptXygs(@RequestBody Object params)
    {
        return companyApi.getCompOperExcepXygs(params);
    }

}
